package edu.cqie.smartfarm.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import edu.cqie.smartfarm.constant.CommonConstant;
import edu.cqie.smartfarm.constant.MessageConstant;
import edu.cqie.smartfarm.dto.FarmDTO;
import edu.cqie.smartfarm.dto.FarmQueryDTO;
import edu.cqie.smartfarm.dto.FarmUpdateDTO;
import edu.cqie.smartfarm.entity.DictionaryData;
import edu.cqie.smartfarm.entity.Farm;
import edu.cqie.smartfarm.mapper.DictionaryDataMapper;
import edu.cqie.smartfarm.mapper.FarmMapper;
import edu.cqie.smartfarm.result.PageVO;
import edu.cqie.smartfarm.service.IFarmService;
import edu.cqie.smartfarm.utils.ThreadLocalUtil;
import edu.cqie.smartfarm.vo.FarmVO;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yyw
 * @since 2024-12-26
 */
@Service
@RequiredArgsConstructor
public class FarmServiceImpl extends ServiceImpl<FarmMapper, Farm> implements IFarmService {

    private final FarmMapper farmMapper;
    private final DictionaryDataMapper dictionaryDataMapper;
    private final StringRedisTemplate stringRedisTemplate;
    /**
     * 获取牧场列表
     * @param farmQueryDTO 查询条件
     * @return 牧场列表
     */
    @Override
    public PageVO<FarmVO> getFarmList(FarmQueryDTO farmQueryDTO) {
        // 1. 创建分页对象
        PageVO<FarmVO> pageVO = new PageVO<>();
        // 2.开起分页
        PageHelper.startPage(farmQueryDTO.getPageNumber(), farmQueryDTO.getPageSize());
        // 3.调用mapper
        List<FarmVO> farmVOList = farmMapper.getFarmList(farmQueryDTO);
        //Page中提供了方法，可以获取PageHelper分页查询后 得到的总记录条数和当前页数据
        Page<FarmVO> page = (Page<FarmVO>) farmVOList;
        // 把数据填充到pageVO中
        pageVO.setCurrent((long) page.getPageNum());
        pageVO.setSize((long) page.getPageSize());
        pageVO.setTotal(page.getTotal());
        pageVO.setPages((long) page.getPages());
        pageVO.setRecords(farmVOList);

        return pageVO;
    }

    /**
     * 获取牧场详情
     * @param id 牧场id
     * @return 牧场详情
     */
    @Override
    public FarmVO getFarmVO(Integer id) {
        Farm farm = getById(id);
        DictionaryData dictionaryData = dictionaryDataMapper.selectById(farm.getDictionaryDataId());
        FarmVO farmVO = BeanUtil.copyProperties(farm, FarmVO.class);
        farmVO.setValue(dictionaryData.getValue());
        return farmVO;
    }

    /**
     * 添加牧场
     * @param farmDTO 牧场信息
     */
    @Override
    public void addFarm(FarmDTO farmDTO) {
        LambdaQueryWrapper<Farm> queryWrapper = new LambdaQueryWrapper<Farm>()
                .eq(Farm::getFarmName, farmDTO.getFarmName());
        if (count(queryWrapper) > 0) {
            throw new RuntimeException(MessageConstant.FARM_EXISTS);
        }
        Farm farm = BeanUtil.copyProperties(farmDTO, Farm.class);
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get(CommonConstant.USER_ID);
        farm.setUserId(userId);
        save(farm);
    }

    /**
     * 修改牧场
     * @param farmUpdateDTO 牧场信息
     */
    @Override
    public void updateFarm(FarmUpdateDTO farmUpdateDTO) {
        // 查询rides中是否存在该id牧场缓存
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        String s = operations.get(CommonConstant.PROJECT_NAME + ":farm::" + farmUpdateDTO.getFarmId());
        if (s != null){
            // 如果存在缓存则删除
            operations.getOperations().delete(CommonConstant.PROJECT_NAME + ":farm::" + farmUpdateDTO.getFarmId());
        }
        // 判断牧场名称是否重复
        if (farmUpdateDTO.getFarmName() != null){
            LambdaQueryWrapper<Farm> queryWrapper = new LambdaQueryWrapper<Farm>()
                    .eq(Farm::getFarmName, farmUpdateDTO.getFarmName());
            if (count(queryWrapper) > 0) {
                throw new RuntimeException(MessageConstant.FARM_EXISTS);
            }
        }

        // 修改
        Farm farm = BeanUtil.copyProperties(farmUpdateDTO, Farm.class);
        farm.setId(farmUpdateDTO.getFarmId());
        updateById(farm);
    }
}
